package com.leige.utils.email;

import java.util.regex.Pattern;

import javax.persistence.Column;

import org.springframework.util.Assert;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

/**
	 * A value object abstraction of an email address.
	 * 
	 * @author Oliver Gierke
	 */
	@JsonSerialize(using = ToStringSerializer.class)
	public class EmailAddress {

		private static final String EMAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		private static final Pattern PATTERN = Pattern.compile(EMAIL_REGEX);

		@Column(name = "email")
		private String emailAddress;
		
		private String noteName;

		/**
		 * Creates a new {@link EmailAddress} from the given string source.
		 * 
		 * @param emailAddress must not be {@literal null} or empty.
		 */
		public EmailAddress(String emailAddress) {
			Assert.isTrue(isValid(emailAddress), "Invalid email address!");
			this.emailAddress = emailAddress;
		}
		public EmailAddress(String emailAddress,String noteName) {
			this(emailAddress);
			this.noteName=noteName;
		}

		protected EmailAddress() {

		}

		/**
		 * Returns whether the given {@link String} is a valid {@link EmailAddress} which means you can safely instantiate the
		 * class.
		 * 
		 * @param source
		 * @return
		 */
		public static boolean isValid(String source) {
			return PATTERN.matcher(source).matches();
		}
		
		public String getNoteName() {
			if(noteName!=null)
				return noteName;
			return emailAddress.substring(0,emailAddress.indexOf('@'));
		}
		 
		@Override
		public String toString() {
			return emailAddress;
		}
	}